﻿#include "stateserver.h"
#include <QTimer>


StateServer::StateServer(quint16 port, QObject* parent)
	: m_port(port), QObject(parent)
{
	connect(m_server, &QTcpServer::newConnection, this, &StateServer::HandleNewConnection);
}
StateServer::~StateServer()
{
	m_server->deleteLater();
}

bool StateServer::Start()
{
	if (!m_server->listen(QHostAddress::Any, m_port)) {
		emit errorOccurred("Status push service failed to start: " + m_server->errorString());
		return false;
	}
	// 启动状态推送定时器
	m_pushTimer = new QTimer(this);
	connect(m_pushTimer, &QTimer::timeout, this, &StateServer::pushStatusData);
	m_pushTimer->start(100); // 10Hz更新频率

	emit serviceStarted("Status push service running on port " + QString::number(m_port));
	return true;
}
void StateServer::Stop()
{
	m_pushTimer->stop();
	m_server->close();
	emit serviceStopped("Status push service stopped");
}
void StateServer::SetStateData(const QByteArray& data)
{
	m_currentStatus = data;
}

void StateServer::HandleNewConnection() {
	while (m_server->hasPendingConnections()) {
		QTcpSocket* client = m_server->nextPendingConnection();
		connect(client, &QTcpSocket::disconnected, this, [this, client]() {
			m_connectionPool->RemoveClinet(client);
			emit clientDisconnected();
			});

		m_connectionPool->AddClient(client);
		emit clientConnected();
	}
}

void StateServer::pushStatusData() {
	// 更新模拟状态数据
	m_connectionPool->SendToAll(m_currentStatus);
}

ClientPool::ClientPool(QObject* parent) :
	QObject(parent)
{

}
ClientPool::~ClientPool()
{

}
void ClientPool::AddClient(QTcpSocket* socket)
{
	QMutexLocker loc(&m_mutex);
	m_clients.append(socket);
	emit clientCountChanged(m_clients.size());
}
void ClientPool::RemoveClinet(QTcpSocket* socket)
{
	QMutexLocker locker(&m_mutex);
	m_clients.removeAll(socket);
	socket->deleteLater();
	emit clientCountChanged(m_clients.size());
}
void ClientPool::SendToAll(const QByteArray& data)
{
	QMutexLocker locker(&m_mutex);
	for (QTcpSocket* client : m_clients) {
		if (client->state() == QTcpSocket::ConnectedState) {
			client->write(data);
		}
	}
}

int ClientPool::ClientCount() const
{
	QMutexLocker loc(&m_mutex);
	return m_clients.size();
}
